﻿using HtmlAgilityPack;
using NewsReader.ViewModels;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Documents;
using Windows.UI.Xaml.Media;

namespace NewsReaderApp.Helpers
{
    public sealed class NewsTextToXamlConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, string language)
        {
            var fullText = value as String;
            if (fullText == null)
                return null;

            FrameworkElement output;
            if (fullText == FeedItem.ERROR_STRING)
            {
                output = new TextBlock()
                {
                    Text = FeedItem.ERROR_STRING
                };
            }
            else
            {
                output = HtmlToXamlConverter.GetTextElementFromHTML(fullText);
            }


            object style;
            Application.Current.Resources.TryGetValue("ArticleText", out style);
            output.Style = style as Style;
            return output;
        }

        public object ConvertBack(object value, Type targetType, object parameter, string language)
        {
            throw new NotImplementedException();
        }
    }

    public static class HtmlToXamlConverter
    {
        private static readonly char[] SKIP_CHARS = new char[] { '\ufffd' };

        public static FrameworkElement GetTextElementFromHTML(string textOrHtml, string direction = "ltr")
        {
            var fd = FlowDirection.LeftToRight;
            if (string.Compare(direction, "rtl", StringComparison.CurrentCultureIgnoreCase) == 0)
            {
                fd = FlowDirection.RightToLeft;
            }

            TextBlock textBlock = GenerateTextBlockToHoldText(fd);

            var doc = new HtmlDocument();
            doc.LoadHtml(textOrHtml);

            if (doc.DocumentNode.Descendants("p").Any())
            {
                foreach (var node in doc.DocumentNode.Descendants("p"))
                {
                    var pureText = HtmlAgilityPack.HtmlEntity.DeEntitize(node.InnerText);
                    AddParagraphToTextBlock(textBlock, pureText);
                }

            }
            else //must be text
            {
                foreach (var paragraph in textOrHtml.Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries))
                {
                    AddParagraphToTextBlock(textBlock, paragraph);
                }

            }

            PadTextBlock(textBlock);
            return textBlock;
        }

        private static TextBlock GenerateTextBlockToHoldText(FlowDirection fd)
        {
            TextBlock textBlock = new TextBlock();
            textBlock.FlowDirection = fd;
            if (fd == FlowDirection.RightToLeft)
            {
                textBlock.Padding = new Thickness(20, 10, 5, 10);
            }
            else
            {
                textBlock.Padding = new Thickness(5, 10, 20, 10);
            }
            return textBlock;
        }

        private static void PadTextBlock(TextBlock textBlock)
        {
            if (textBlock.Inlines.Count > 2)
            {
                textBlock.Inlines.RemoveAt(textBlock.Inlines.Count - 1);
                textBlock.Inlines.RemoveAt(textBlock.Inlines.Count - 1);
            }
        }

        private static void AddParagraphToTextBlock(TextBlock textBlock, string paragraph)
        {
            var r = new Run();
            r.Text = paragraph;

            textBlock.Inlines.Add(r);
            textBlock.Inlines.Add(new LineBreak());
            textBlock.Inlines.Add(new LineBreak());
        }

        public static string CleanupHTML(this string input)
        {
            return HtmlAgilityPack.HtmlEntity.DeEntitize(input);
        }
    }
}
